<template>
  <div class="auxiliary">
    <page-header title="课程列表">
      <page-search :config="searchConfig" :model="searchModel" @search="getData">
        <el-button @click="toCreate">添加课程</el-button>
      </page-search>
    </page-header>
    <el-table :data="tableData" :cell-class-name="setCellClassName" :max-height="clientHeight - 320">
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :min-width="column.minWidth"
        :label="column.label">
        <template slot-scope="{ row }">
          <div v-if="column.prop === 'name'" class="align-center">
            <el-image
              style="width: 70px; height: 46px"
              :src="row.coverUrl">
            </el-image>
            <span class="pl-8">{{row.name}}</span>
          </div>
          <template v-else>{{row[column.prop]}}</template>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="80px">
        <template slot-scope="{ row }">
          <action-text @click="toModify(row)">修改</action-text>
          <action-text @click="deleteData(row)" type='danger'>删除</action-text>
        </template>
      </el-table-column>
    </el-table>
    <page-pagination
      :pageSize="pageSize"
      :currentPage="pageNum"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script>
import paginationMixin from '@/mixins/pagination';
import { getCourseList, deleteCourse } from '@/api/course';
import { getFirstCategoryList, getSecondCategoryList, getStudentAgeOptions } from '@/utils';
import { cloneDeep } from 'lodash';

const courseFlagMap = {
  hotCourse: '热门课程',
  latestCourse: '最新课程',
  grouponCourse: '拼团课程',
  timeLimitCourse: '限时课程',
  commendArtCourse: '美术主推',
  commendCalligraphyCourse: '书法主推',
  advertisementCourse: '弹窗课程',
};

const courseFlagKeys = [
  'hotCourse', 'latestCourse', 'grouponCourse', 'timeLimitCourse',
  'commendArtCourse', 'commendCalligraphyCourse', 'advertisementCourse',
];

const courseFlags = [
  { value: 1, label: '限时课程' },
  { value: 2, label: '最新课程' },
  { value: 3, label: '热门课程' },
  { value: 4, label: '拼团课程' },
  { value: 5, label: '美术主推' },
  { value: 6, label: '书法主推' },
  { value: 7, label: '弹窗课程' },
];

export default {
  data() {
    return {
      searchConfig: [
        {
          type: 'input',
          prop: 'name',
          label: '课程名称',
        },
        {
          type: 'select',
          prop: 'firstCategory',
          label: '一级分类',
          options: [],
        },
        {
          type: 'select',
          prop: 'secondCategory',
          label: '二级分类',
          options: [],
        },
        {
          type: 'select',
          prop: 'valid',
          label: '状态',
          options: [
            { value: '', label: '全部' },
            { value: 1, label: '有效' },
            { value: 0, label: '无效' },
          ],
        },
        {
          type: 'select',
          prop: 'courseFlag',
          label: '课程类别',
          options: [
            { value: '', label: '全部' },
            ...courseFlags,
          ],
        },
        {
          type: 'daterange',
          prop: 'time',
          label: '入驻时间',
        },
      ],
      searchModel: {
        name: '',
        firstCategory: '',
        secondCategory: '',
        valid: 1,
        time: [],
        courseFlag: '',
      },
      columns: [
        { prop: 'name', label: '课程', minWidth: '120px' },
        { prop: 'studentAge', label: '学龄段', minWidth: '80px' },
        { prop: 'firstCategoryName', label: '一级分类', minWidth: '80px' },
        { prop: 'secondCategoryName', label: '二级分类', minWidth: '80px' },
        { prop: 'salePrice', label: '售价（元）', minWidth: '80px' },
        { prop: 'price', label: '原价（元）', minWidth: '80px' },
        { prop: 'grouponPrice', label: '拼团价（元）', minWidth: '80px' },
        { prop: 'captherCount', label: '节数', minWidth: '70px' },
        { prop: 'courseFlag', label: '课程类别', minWidth: '240px' },
        { prop: 'status', label: '状态', minWidth: '70px' },
        { prop: 'createTime', label: '创建时间', minWidth: '100px' },
      ],
      tableData: [],
      firstCategoryList: [],
      secondCategoryList: [],
      studentAgeOptions: [],
    };
  },
  mixins: [paginationMixin],
  watch: {
    'searchModel.firstCategory'(val) {
      this.searchModel.secondCategory = '';
      this.searchConfig[2].options = [{ label: '全部', id: '' }].concat(this.secondCategoryList.filter((item) => item.parentId === val));
    },
  },
  computed: {
    requestParam() {
      const params = cloneDeep(this.searchParams);
      [params.startTime, params.endTime] = params.time;
      delete params.time;
      return params;
    },
  },
  methods: {
    toCreate() {
      this.$router.push({
        name: 'course-edit',
      });
    },
    setCellClassName({ column }) {
      if (column.property === 'name') {
        return 'image-cell';
      }
      return '';
    },
    toModify(data) {
      this.$router.push({
        name: 'course-edit',
        query: {
          courseId: data.id,
        },
      });
    },
    async getStudentAgeOptions() {
      this.studentAgeOptions = await getStudentAgeOptions();
    },
    async deleteData(row) {
      this.$confirm('确定删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        await deleteCourse({
          courseId: row.id,
        });
        this.$message.success('删除成功');
        await this.getData();
      }).catch(() => {});
    },
    async getData() {
      const result = await getCourseList(this.requestParam);
      const { total, list } = result;
      this.total = total;
      this.tableData = list && list.map((item) => {
        const {
          createTime, studentAge, valid, price, salePrice, grouponPrice,
        } = item;
        const courseFlag = [];
        courseFlagKeys.forEach((key) => {
          if (item[key]) {
            courseFlag.push(courseFlagMap[key]);
          }
        });
        return {
          ...item,
          status: valid ? '销售中' : '已下架',
          price: price / 100,
          salePrice: salePrice / 100,
          grouponPrice: grouponPrice / 100,
          studentAge: studentAge.name,
          createTime: this.$formatTime(createTime),
          courseFlag: courseFlag.join('，'),
        };
      });
    },
    async getCategoryOptions() {
      const [firstCategoryList, secondCategoryList, studentAgeOptions] = await Promise.all([
        getFirstCategoryList(),
        getSecondCategoryList(),
        getStudentAgeOptions(),
      ]);
      this.studentAgeOptions = studentAgeOptions;
      this.secondCategoryList = secondCategoryList;
      this.searchConfig[1].options = [{ label: '全部', id: '' }].concat(firstCategoryList);
      this.searchConfig[2].options = secondCategoryList;
    },
  },
  async created() {
    await this.getCategoryOptions();
    await this.getData();
  },
};
</script>
